package com.inspur.resourcequery.dbHelper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper {
	
	
	private SQLiteDatabase db;
	private final Context context;
	private DBOpenHelper dbOpenHelper;
	private String tableName;
	private String[] initSql;
	private int version = 1;
	
	private final String REPORT_TABLE_NAME = "RES_QUERY";
	private final String REPORT_TABLE_SQL = 
			"create table " + REPORT_TABLE_NAME + "(" +
			"cacheKey text, " +
			"cacheValue text, " +
			"userName text, " +
			"updateDate timestamp " +
			");";
	
	
	/**
	 * 创建数据库腈操作对象
	 * @param context 上下文 
	 * @param tableName 表名
	 * @param tableSql 表创建语句
	 */
	public DBHelper(Context context) {
		this.context = context;
		this.tableName = REPORT_TABLE_NAME;
		this.initSql = new String[]{REPORT_TABLE_SQL};
	}

	/**
	 * 创建数据库腈操作对象
	 * @param context 上下文 
	 * @param tableName 表名
	 * @param tableSql 表创建语句
	 */
	public DBHelper(Context context, String tableName, String tableSql) {
		this.context = context;
		this.tableName = tableName;
		this.initSql = new String[]{tableSql};
	}
	
	/**
	 * 创建数据库腈操作对象
	 * @param context 上下文 
	 * @param tableName 表名
	 * @param initSql 初始化Sql语句
	 */
	public DBHelper(Context context, String tableName, String[] initSql) {
		this.context = context;
		this.tableName = tableName;
		this.initSql = initSql;
	}
	
	/**
	 * 创建数据库腈操作对象
	 * @param context 上下文 
	 * @param tableName 表名
	 * @param tableSql 表创建语句
	 */
	public DBHelper(Context context, String tableName, String[] initSql, int version) {
		this.context = context;
		this.tableName = tableName;
		this.initSql = initSql;
		this.version = version;
	}

	/**
	 * 获取数据库操作对象
	 * @return
	 */
	public SQLiteDatabase open() {
		dbOpenHelper = new DBOpenHelper(context, REPORT_TABLE_NAME, null, version);
		try {
			db = dbOpenHelper.getWritableDatabase();
		} catch (SQLiteException e) {
			// TODO Auto-generated catch block
			db = dbOpenHelper.getReadableDatabase();
		}
		return db;
	}

	/**
	 * 关闭数据库连接
	 */
	public void close() {
		if (db != null) {
			db.close();
			db = null;
		}
	}
	
	/**
	 * 关闭指定的数据库连接
	 * @param db SQLiteDatabase对象
	 */
	public void close(SQLiteDatabase db) {
		if (db != null) {
			db.close();
			db = null;
		}
	}

	private class DBOpenHelper extends SQLiteOpenHelper {

		public DBOpenHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
		}	

		@Override
		public void onCreate(SQLiteDatabase db) {
			for(int i = 0; i < initSql.length; i++){
				db.execSQL(initSql[i]);
			}
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("drop table if exists " + tableName);
			onCreate(db);
		}
	}
}